package com.easy.controller;

import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class UploadController {
    @RequestMapping("upload")
    @ResponseBody
    public LayData upload(@RequestParam("file") MultipartFile file){

        //获取文件原来的后缀名
        String fileName=file.getOriginalFilename();
        String fileType=fileName.substring(fileName.lastIndexOf("."));
        //在前面拼接上一个新的名字(尽量不要重复)
        String uuid=UUID.randomUUID().toString();
        String newFileName=uuid+fileType;
        try {
            //将上传的文件写入到新文件中
            file.transferTo(new File(SYS.FILE_UPLOAD_DIR+newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回结果
        return new LayData(SYS.FILE_UPLOAD_URL+"/"+newFileName);
    }
}
